package com.dfbz.controller.user;

import com.dfbz.constant.Const;
import com.dfbz.controller.BaseServlet;
import com.dfbz.model.UserFocus;
import com.dfbz.service.UserService;
import com.dfbz.service.impl.UserServiceImpl;
import com.dfbz.utils.StrUtil;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

@WebServlet("/user/*")
public class UserServlet extends BaseServlet {

    private UserService userService = new UserServiceImpl();

    public void list(HttpServletRequest request, HttpServletResponse response) {
        try {
            String currentPage = request.getParameter("currentPage");
            String search = request.getParameter("search");
            int page = 1;
            if (null != currentPage) {
                page = Integer.parseInt(currentPage);
            }
            if (null != search) {
                String encode = URLEncoder.encode(search, "UTF-8");
                response.sendRedirect(request.getContextPath() + "/view/userList?page=" + page + "&search=" + encode);
            } else {
                response.sendRedirect(request.getContextPath() + "/view/userList?page=" + page);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void follow(HttpServletRequest request, HttpServletResponse response) {
        try {
            response.setHeader("content-Type", "text/html");
            String userFocusId = request.getParameter("uId");
            if (null != userFocusId) {
                String userId = request.getSession().getAttribute("userId").toString();
                if (userId.equals(userFocusId)) {
                    response.getWriter().write("不能关注自己");
                } else {
                    UserFocus focus = userService.findFollowData(Integer.parseInt(userId), Integer.parseInt(userFocusId));
                    if (null == focus) {
                        userService.followUser(Integer.parseInt(userId), Integer.parseInt(userFocusId));
                        response.getWriter().write("success");
                    } else {
                        response.getWriter().write("关注失败");
                    }
                }
            } else {
                response.getWriter().write("关注失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void unfollow(HttpServletRequest request, HttpServletResponse response) {
        try {
            response.setHeader("content-Type", "text/html");
            String ufId = request.getParameter("ufId");
            if (null != ufId) {
                userService.unFollow(Integer.parseInt(ufId));
                response.getWriter().write("success");
            } else {
                response.getWriter().write("取关失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void myUser(HttpServletRequest req,HttpServletResponse resp){
        try {
            String pageCurrent = req.getParameter("page");
            int page = 1;
            if (StrUtil.isNotEmpty(pageCurrent)){
                page = Integer.parseInt(pageCurrent);
            }
            resp.sendRedirect(req.getContextPath()+"/view/myUserList?page="+page);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void getDetail(HttpServletRequest request, HttpServletResponse response) {
        try {
            String uId = request.getParameter("userId");
            String userId = request.getSession().getAttribute("userId").toString();
            if (!userId.equals(uId)) {
                userService.addLook(Integer.parseInt(uId));
            }
            response.sendRedirect(request.getContextPath() + "/view/userDetail?uId=" + uId);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void uploadFile(HttpServletRequest request, HttpServletResponse response) {
        try {
            ServletFileUpload servletFileUpload = new ServletFileUpload(new DiskFileItemFactory());
            servletFileUpload.setSizeMax(1024 * 1024 * 20L);
            try {
                List<FileItem> files = servletFileUpload.parseRequest(request);
                FileItem item = files.get(0);
                String[] split = item.getName().split("\\.");
                if (split.length == 2) {
                    String fileName = StrUtil.getUUID() + "." + split[1];
                    String filePath = Const.BASE_FILEPATH + Const.PATH + fileName;
                    File file = new File(filePath);
                    if (!file.exists()) {
                        item.write(file);
                    }
                    String userId = request.getSession().getAttribute("userId").toString();
                    String path = Const.PATH + fileName;
                    userService.updateUserImg(Integer.parseInt(userId), path);

                    Map<String, Object> map = userService.findUserBaseById(Integer.parseInt(userId));
                    request.getSession().setAttribute("userBaseInfo", map);

                    response.getWriter().write(path);
                } else {
                    response.getWriter().write("fail");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
